<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="计划单号" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="plan_production" column-name="code" :is-edit="id" />
        </el-form-item>
        <el-form-item label="销售订单" class="clickChoose" prop="customerName">
          <el-input v-model="formData.saleOrderCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseOrders"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="计划类型" prop="planTypeCode">
          <DictSelect
            :band-value.sync="formData.planTypeCode"
            dict-type="planTypeCode"
          />
        </el-form-item>
        <el-form-item label="计划人员">
          <el-input v-model="formData.planPersonName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="计划日期" prop="planTime">
          <el-date-picker
            v-model="formData.planTime"
            type="date"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item />
        <el-form-item v-if="enterWarehouseInvoices==1" label="生产任务单" class="double">
          <div class="main_enterWarehouseInvoices">
            <el-radio v-model="formData.isIssue" label="0">自动下发</el-radio>
            <el-radio v-model="formData.isIssue" label="1">自动下发需人工确认</el-radio>
            <el-radio v-model="formData.isIssue" label="2">不下发</el-radio>
          </div>
        </el-form-item>
        <el-form-item label="生产模式" class="double">
          <div class="main_enterWarehouseInvoices">
            <el-radio v-model="formData.model" label="0" @input="inputRadio">按工艺要求</el-radio>
            <el-radio v-model="formData.model" label="1" @input="inputRadio">按BOM和工艺路线</el-radio>
          </div>
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        物料明细
        <div v-if="materialName" class="MaterialName">
          <span class="MaterialNameIcon el-icon-warning" />
          <div class="MaterialNameName">
            {{ materialName }}
          </div>
          <div v-if="formData.model == '0'" class="MaterialNameText">物料未维护工艺版本号，请前往工艺要求查看！</div>
          <div v-if="formData.model == '1'" class="MaterialNameText">物料未维护 BOM ，请前往 BOM 查看！</div>
        </div>
        <div v-else />
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="add">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="remove1">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div ref="table_container2" class="table_container">
        <el-table
          ref="table"
          :data="tableData"
          :height="tableHeight"
          stripe
          border
          :header-cell-class-name="headerCellClassName"
          :cell-class-name="cellClassName"
          @selection-change="selectionChange1"
        >
          <el-table-column type="selection" align="center" />
          <el-table-column label="物料编码" min-width="120" prop="materialCode" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料分类" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialTypeName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="formData.model=='0'" label="工艺版本号" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.engineeringRequirementVersionCode }}</span>
            </template>
          </el-table-column>
          <!--          <el-table-column v-if="formData.model=='0'" label="工艺版本号" min-width="120" prop="technologyVersion">-->
          <!--            <template slot-scope="scope">-->
          <!--              <el-select v-model="scope.row.engineeringRequirementId" placeholder="请选择" clearable @change="changeVersion(scope.row)" @visible-change="selectVersion(scope.row,$event)">-->
          <!--                <el-option-->
          <!--                  v-for="item in scope.row.technologyVersionList"-->
          <!--                  :key="item.engineeringRequirementId"-->
          <!--                  :label="item.engineeringRequirementVersionCode"-->
          <!--                  :value="item.engineeringRequirementId"-->
          <!--                />-->
          <!--              </el-select>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <!--          <el-table-column v-if="formData.model=='1'" label="BOM版本号" min-width="120" prop="technologyVersion">-->
          <!--            <template slot-scope="scope">-->
          <!--              <el-select v-model="scope.row.engineeringBomId" placeholder="请选择" @change="changeBOM(scope.row)">-->
          <!--                <el-option-->
          <!--                  v-for="item in scope.row.BOMList"-->
          <!--                  :key="item.id"-->
          <!--                  :label="item.versionCode"-->
          <!--                  :value="item.id"-->
          <!--                />-->
          <!--              </el-select>-->
          <!--            </template>-->
          <!--          </el-table-column>-->

          <el-table-column v-if="formData.model=='1'" label="BOM版本号" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.engineeringBomVersion }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="formData.model=='1'" label="工艺路线" min-width="140" prop="engineeringPathCode">
            <template slot-scope="scope">
              <!--              <el-input v-model="scope.row.engineeringPathCode" placeholder="请选择" readonly @click.native="chooseProcessFlow(scope.row,scope.$index)" />-->

              <span>{{ scope.row.engineeringPathCode }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="formData.model=='1'" label="工艺路线版本号" min-width="120" prop="engineeringPathVersion">
            <template slot-scope="scope">
              <!--              <el-input v-model="scope.row.engineeringPathVersion" placeholder="请选择" readonly />-->
              <span>{{ scope.row.engineeringPathVersion }}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户交期" min-width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.saleCustomerDeliveryTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单数量" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.orderNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="库存数量" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.materialInventory }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="planNumber">
            <template slot-scope="scope">
              <span v-if="scope.row.disabled||formData.saleOrderCode">{{ scope.row.planNumber }}</span>
              <el-input v-else v-model="scope.row.planNumber" placeholder="请输入" clearable @blur="planNumberChannge(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="计划交期" min-width="140">
            <template slot-scope="scope">
              <el-date-picker
                v-model="scope.row.planDealTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
                :editable="false"
                @change="changeplanDealTime(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" clearable @blur="changeRemark(scope.row)" @change="changeRemark(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit('0')">保存</el-button>
      <el-button @click.stop="onSubmit('1')">提交</el-button>
    </div>
  </div>
</template>

<script>
import { getInfoByConfigKey } from '@/api/outsourceManage/outsourceReturnMaterial'
import { addOrUpdate, getInfo, requirement, getLatestModel } from '@/api/planManagement/planProductionOrder'
import searchMaterial from './searchMaterial.vue'
import searchMaterial2 from './searchMaterialList.vue'
import chooseOrder from './chooseOrder.vue'
import { listForPlanProduction } from '@/api/saleManage/saleOrder'
import moment from 'moment'
import ImportData from '@/components/JLink/common/ImportData'
import { list as BOMList } from '@/api/engineeringManage/BOMManage'
import { list as choosePath_API } from '@/api/engineeringManage/processFlow'
import ChooseProcessFlow from '@/views/engineeringManage/processFlow/chooseProcessFlow.vue'
// import { get } from 'js-cookie'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    return {
      formData: {
        id: '',
        code: '',
        isIssue: '',
        saleOrderCode: '',
        saleOrderId: '',
        planTypeCode: '',
        planPersonName: '',
        planPersonId: '',
        planTime: '',
        remark: '',
        model: '',
        unmergeData: []
      },
      enterWarehouseInvoices: '',
      tableHeight: '320',
      userOptions: [],
      equipmentList: [],
      selectionsAll1: [],
      ids: [],
      roleOptions: [],
      selectionsAll: [], // 表格所有页选中的行
      orderSelectionsAll: [], // 销售订单
      inx: 1,
      tableData: [],
      listData: [],
      loading: false,
      fristFalg: false,
      materialName: '', // 未维护工艺要求
      materialNameList: [], // 未维护工艺要求
      unMergeList: [], // 未合并的数据数组
      rules: {
        code: [
          { required: true, message: '计划单号不能为空', trigger: 'blur' }
        ],
        planTime: [
          { required: true, message: '计划日期不能为空', trigger: 'change' }
        ],
        planTypeCode: [
          { required: true, message: '计划类型不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getInfoByConfigKey()
    if (!this.id) { // 没有id就是新增
      // 获取上一次的 生产模式 选项
      getLatestModel().then(res => {
        this.formData.model = res.data.model || '0'
        this.loading = false
      })
    } else { // 有id就是编辑
      this.getInfo()
    }
  },
  mounted() {
    this.formData.planPersonName = this.$store.state.user.name
    this.formData.planPersonId = this.$store.state.user.userId
    this.formData.planTime = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    headerCellClassName(data) {
      if (['planNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
      if (['technologyVersion'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    cellClassName(data) {
      if (['工艺路线', '工艺路线版本号'].indexOf(data.column.label) != -1) {
        return 'processFlowClass'
      }
    },
    getInfoByConfigKey() {
      getInfoByConfigKey('productionSettingStatus').then(res => {
        this.enterWarehouseInvoices = res.data.productionSettingStatus
        if (this.enterWarehouseInvoices == 1) {
          this.formData.isIssue = '0'
        } else {
          this.formData.isIssue = '2'
        }
      })
    },
    // 计划交期变更
    changeplanDealTime(row) {
      if (this.formData.saleOrderId) {
        this.unMergeList.forEach((item) => {
          if (item.saleOrderDetailId == row.saleOrderDetailId) {
            item.planDealTime = row.planDealTime
          }
        })
      } else {
        this.unMergeList.forEach((item) => {
          if (item.materialId == row.materialId) {
            item.planDealTime = row.planDealTime
          }
        })
      }
    },
    // 备注变更
    changeRemark(row) {
      if (this.formData.saleOrderId) {
        this.unMergeList.forEach((item) => {
          if (item.saleOrderDetailId == row.saleOrderDetailId) {
            item.remark = row.remark
          }
        })
      } else {
        this.unMergeList.forEach((item) => {
          if (item.materialId == row.materialId) {
            item.remark = row.remark
          }
        })
      }
    },
    planNumberChannge(row) {
      this.unMergeList.forEach((item) => {
        if (item.materialId == row.materialId) {
          item.planNumber = row.planNumber
        }
      })
    },
    // 工艺版本变更
    changeVersion(row) {
      const selectedRow = row.technologyVersionList.filter(item => item.id == row.engineeringRequirementId)[0]
      if (this.formData.saleOrderId) {
        this.unMergeList.forEach((item) => {
          if (item.saleOrderDetailId == row.saleOrderDetailId) {
            item.engineeringRequirementCode = selectedRow.engineeringRequirementCode
            item.engineeringRequirementId = selectedRow.engineeringRequirementId
            item.engineeringRequirementVersionCode = selectedRow.engineeringRequirementVersionCode
            item.isEqual = selectedRow.isEqual
          }
        })
      } else {
        this.unMergeList.forEach((item) => {
          if (item.materialId == row.materialId) {
            item.engineeringRequirementCode = selectedRow.engineeringRequirementCode
            item.engineeringRequirementId = selectedRow.engineeringRequirementId
            item.engineeringRequirementVersionCode = selectedRow.engineeringRequirementVersionCode
            item.isEqual = selectedRow.isEqual
          }
        })
      }
    },
    // 工艺版本
    selectVersion(row, scope) {
      if (scope) {
        requirement(row.materialId).then(res => {
          // row.
          res.data.map((item) => {
            item.engineeringRequirementVersionCode = item.versionCode
            item.engineeringRequirementId = item.id
            item.engineeringRequirementCode = item.code
          })
          row.technologyVersionList = res.data
        })
      }
    },
    // BOM变更
    changeBOM(row) {
      const selectedRow = row.BOMList.filter(item => item.id == row.engineeringBomId)[0]
      if (this.formData.saleOrderId) {
        this.unMergeList.forEach((item) => {
          if (item.saleOrderDetailId == row.saleOrderDetailId) {
            item.engineeringBomId = selectedRow.id
            item.engineeringBomCode = selectedRow.code
            item.engineeringBomVersion = selectedRow.versionCode
            item.isEqual = selectedRow.isEqual
          }
        })
      } else {
        this.unMergeList.forEach((item) => {
          if (item.materialId == row.materialId) {
            item.engineeringBomId = selectedRow.id
            item.engineeringBomCode = selectedRow.code
            item.engineeringBomVersion = selectedRow.versionCode
            item.isEqual = selectedRow.isEqual
          }
        })
      }
    },

    // 选择销售订单
    showOrder(data) {
      this.orderSelectionsAll = data
      if (data.length > 0) {
        this.formData.saleOrderCode = data.map(item => item.code).join(',')
        this.formData.saleOrderId = data.map(item => item.id).join(',')
      } else {
        this.formData.saleOrderCode = ''
        this.formData.saleOrderId = ''
      }
      listForPlanProduction({ saleOrderIds: this.formData.saleOrderId, planProductionId: this.formData.id }).then(res => {
        this.unMergeList = []
        this.materialNameList = []
        res.data.unMerge.map((item) => {
          // 如果是新增则将数据的未发数量带入计划数量
          // if (!this.formData.id) {
          // }
          item.planNumber = item.willDeliverNumber
          item.planDealTime = item.saleCustomerDeliveryTime
          item.saleOrderDetailId = item.id
          delete item.id
          // 显示默认工艺版本号
          if (!item.engineeringRequirementId) {
            item.technologyVersionList = []
          } else {
            item.technologyVersionList = [{
              engineeringRequirementId: item.engineeringRequirementId ? item.engineeringRequirementId : undefined,
              engineeringRequirementVersionCode: item.engineeringRequirementVersionCode ? item.engineeringRequirementVersionCode : undefined
            }]
          }
        })
        // 合并数据
        this.tableData = this.sumArr(res.data.unMerge)
        this.unMergeList = res.data.unMerge
        // 按bom和工艺路线时设置bom选择数据
        if (this.formData.model == 1) {
          this.setRowBom()
        }
        // this.tableData = res.data.Merge
      })
    },
    // 未维护工艺要求
    getWaringList(arr) {
      this.materialNameList = []
      this.materialName = ''
      if (this.formData.model == '0') {
        arr.map((item) => {
          if (!item.engineeringRequirementId && !item.engineeringRequirementVersionCode) {
            if (this.materialNameList.length < 2) {
              this.materialNameList.push(item.materialName)
            } else if (this.materialNameList.length == 2) {
              this.materialNameList.push(item.materialName + '等')
            }
            this.materialName = this.materialNameList.join(',')
          }
        })
      }
    },
    getWaringList_BOM() {
      this.materialNameList = []
      this.materialName = ''
      if (this.formData.model == '1') {
        this.tableData.map((item) => {
          if (!item.engineeringBomId && !item.engineeringBomVersion) {
            if (this.materialNameList.length < 2) {
              this.materialNameList.push(item.materialName)
            } else if (this.materialNameList.length == 2) {
              this.materialNameList.push(item.materialName + '等')
            }
            this.materialName = this.materialNameList.join(',')
          }
        })
      }
    },
    // 合并数据
    sumArr(arrList) {
      this.fristFalg = false
      // 转化为时间戳并且判断是否为第一次新增,是第一次则将未发数量合并带入计划数量
      arrList.forEach((a) => {
        if (!a.planNumber) {
          this.fristFalg = true
        } else {
          this.fristFalg = false
        }
        // 新增销售订单下的物料时才转化时间戳计算取最小值
        if (!this.formData.id && this.formData.saleOrderId) {
          a.saleCustomerDeliveryTimeNumber = Date.parse(a.saleCustomerDeliveryTime.replace(/\-/g, '/'))
        }
      })
      const nameArr = [...new Set(arrList.map(i => i.materialId))]// 名称集合
      const list = []
      nameArr.forEach(v => {
        const filterlist = arrList.filter(a => v == a.materialId)
        list.push(filterlist)
      })
      const outArr = []
      // 时间戳转化
      // list.forEach((ele) => {
      //   if (ele.length > 1) {
      //     var min = Math.min.apply(Math, ele.map(o => o.saleCustomerDeliveryTimeNumber))
      //     ele[0].saleCustomerDeliveryTime = new Date(min).toLocaleDateString().slice().replace(/\//g, '-')
      //   }
      //   ele[0].planDealTime = ele[0].saleCustomerDeliveryTime
      // })
      list.forEach((item, index) => {
        if (!this.formData.id && this.formData.saleOrderId) {
          if (item.length > 1) {
            var min = Math.min.apply(Math, item.map(o => o.saleCustomerDeliveryTimeNumber))
            item[0].saleCustomerDeliveryTime = new Date(min).toLocaleDateString().slice().replace(/\//g, '-')
          }
          item[0].planDealTime = item[0].saleCustomerDeliveryTime
        } else if (this.formData.id && !item[0].planDealTime) {
          item[0].planDealTime = item[0].saleCustomerDeliveryTime
        }
        // // 新增第一次合并计算未发数量，否则计算计划数量
        // if (this.fristFalg) {
        //   // 合计订单数量
        //   const orderNumber = item.reduce((total, g) => {
        //     return total + Number(g.orderNumber)
        //   }, 0)
        //   const planNumber = item.reduce((total, g) => {
        //     return total + Number(g.willDeliverNumber)
        //   }, 0)
        //   outArr.push({
        //     ...item[0],
        //     orderNumber: orderNumber,
        //     planNumber: planNumber
        //   })
        // } else {
        // 合计订单数量
        const orderNumber = item.reduce((total, g) => {
          return total + Number(g.orderNumber)
        }, 0)

        const planNumber = item.reduce((total, g) => {
          return total + Number(g.planNumber)
        }, 0)
        // 如果订单数量合计为0则置空
        if (orderNumber == 0) {
          if (planNumber == 0) {
            outArr.push({
              ...item[0],
              orderNumber: '',
              planNumber: ''
            })
          } else {
            outArr.push({
              ...item[0],
              orderNumber: '',
              planNumber: planNumber
            })
          }
        } else {
          outArr.push({
            ...item[0],
            orderNumber: orderNumber,
            planNumber: planNumber
          })
        }
        // }
      })
      this.loading = false
      this.getWaringList(outArr)
      return outArr
    },
    // 物料回显
    showMaterial(data) {
      // 比较老数据赋值id
      this.unMergeList = data
      // data.forEach(ele => {
      //   delete ele.remark
      // })
      // data.map((item) => {
      //   item.planDealTime = item.saleCustomerDeliveryTime
      //   if (!item.engineeringRequirementId) {
      //     item.technologyVersionList = []
      //   } else {
      //     item.technologyVersionList = [{
      //       engineeringRequirementId: item.engineeringRequirementId ? item.engineeringRequirementId : undefined,
      //       engineeringRequirementVersionCode: item.engineeringRequirementVersionCode ? item.engineeringRequirementVersionCode : undefined
      //     }]
      //   }
      // })
      if (this.formData.saleOrderId) {
        this.tableData = this.sumArr(data)
        this.setRowBom()
      } else {
        this.getWaringList(data)
        this.unMergeList = data
        this.tableData = data
      }
    },
    // 物料回显
    showMaterial2(data) {
      this.getWaringList(data)
      this.unMergeList = data
      this.tableData = data
      if (this.formData.model == '1') {
        this.setRowBom()
      }
    },
    chooseOrders() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseOrder, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectionId: this.formData.saleOrderId ? this.formData.saleOrderId : '',
            selectedRow: this.orderSelectionsAll
          } // props
        },
        area: ['880px', '700px'],
        title: '选择销售订单', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    selectionChange1(rows) {
      this.selectionsAll1 = rows
    },
    getInfo() {
      getInfo(this.id).then(res => {
        this.formData = res.data
        this.unMergeList = res.data.unmergeData
        const arr1 = this.formData.saleOrderCode.split(',')
        const arr2 = this.formData.saleOrderId.split(',')
        if (this.formData.saleOrderCode) {
          arr1.map((item, index) => {
            const obj = {
              code: item,
              id: Number(arr2[index])
            }
            this.orderSelectionsAll.push(obj)
          })
        }
        res.data.unmergeData.map((item) => {
          item.technologyVersionList = [{
            engineeringRequirementId: item.engineeringRequirementId ? item.engineeringRequirementId : undefined,
            engineeringRequirementVersionCode: item.engineeringRequirementVersionCode ? item.engineeringRequirementVersionCode : undefined
          }]
        })
        this.tableData = this.sumArr(res.data.unmergeData)
        if (this.formData.model == '1') {
          this.setRowBom()
        }
        if (this.formData.model == '0') {
          this.setRowRequirement()
        }
      })
    },
    remove1() {
      // 删除合并后的页面展示数据
      this.selectionsAll1.forEach(item => {
        this.tableData.splice(this.tableData.indexOf(item), 1)
      })
      const arr = this.$deepClone(this.unMergeList)
      // 删除时比较未合并数据，如果删除的为合并数据则未合并的数据一起删除
      this.selectionsAll1.map((item) => {
        arr.map((ele) => {
          if ((ele.materialId == item.materialId)) {
            ele.deleteFlag = true
          }
        })
      })
      this.unMergeList = arr.filter((item) => !item.deleteFlag)
      this.inputRadio(this.formData.model)
      // 删除后提示数据变化
      // this.materialNameList = []
      // this.materialName = ''
      // this.tableData.map((item) => {
      //   if (!item.engineeringRequirementId) {
      //     item.technologyVersionList = []
      //     if (this.materialNameList.length < 2) {
      //       this.materialNameList.push(item.materialName)
      //     } else if (this.materialNameList.length == 2) {
      //       this.materialNameList.push(item.materialName + '等')
      //     }
      //     this.materialName = this.materialNameList.join(',')
      //   }
      // })
    },
    add() {
      // if (!this.formData.saleOrderCode) {
      //   return this.$message.warning('请选择销售订单')
      // }
      // 第一次新增点击添加未发数量带入计划数量
      // if (this.fristFalg) {
      //   this.unMergeList.map((item) => {
      //     item.planNumber = item.willDeliverNumber
      //   })
      // }
      if (this.formData.saleOrderId) {
        this.$layer.iframe({
          // 弹框
          content: {
            content: searchMaterial, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              selectedRow: this.unMergeList,
              saleOrderIds: this.formData.saleOrderId,
              planProductionId: this.formData.id
            } // props
          },
          area: ['1320px', '700px'],
          title: '选择物料', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      } else {
        this.$layer.iframe({
          // 弹框
          content: {
            content: searchMaterial2, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              selectedRow: this.unMergeList
            } // props
          },
          area: ['1320px', '700px'],
          title: '选择物料', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      }
    },
    onSubmit(e) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          // this.formData.unmergeData = JSON.parse(JSON.stringify(this.unMergeList))
          const unmergeData = JSON.parse(JSON.stringify(this.unMergeList))
          this.tableData.forEach(item => {
            if (this.formData.saleOrderId) {
              unmergeData.forEach((item2) => {
                if (item2.saleOrderDetailId == item.saleOrderDetailId) {
                  item2.engineeringBomId = item.engineeringBomId
                  item2.engineeringBomCode = item.engineeringBomCode
                  item2.engineeringBomVersion = item.engineeringBomVersion
                  item2.engineeringPathId = item.engineeringPathId
                  item2.engineeringPathCode = item.engineeringPathCode
                  item2.engineeringPathVersion = item.engineeringPathVersion
                  item2.engineeringRequirementId = item.engineeringRequirementId
                  item2.engineeringRequirementCode = item.engineeringRequirementCode
                  item2.engineeringRequirementVersionCode = item.engineeringRequirementVersionCode
                }
              })
            } else {
              unmergeData.forEach((item2) => {
                if (item2.materialId == item.materialId) {
                  item2.engineeringBomId = item.engineeringBomId
                  item2.engineeringBomCode = item.engineeringBomCode
                  item2.engineeringBomVersion = item.engineeringBomVersion
                  item2.engineeringPathId = item.engineeringPathId
                  item2.engineeringPathCode = item.engineeringPathCode
                  item2.engineeringPathVersion = item.engineeringPathVersion
                  item2.engineeringRequirementId = item.engineeringRequirementId
                  item2.engineeringRequirementCode = item.engineeringRequirementCode
                  item2.engineeringRequirementVersionCode = item.engineeringRequirementVersionCode
                }
              })
            }
          })
          this.formData.unmergeData = unmergeData
          this.formData.unmergeData.forEach(ele => {
            delete ele.id
          })
          if (this.formData.model == '0' && this.formData.unmergeData.filter(item => !item.engineeringRequirementId).length > 0 && e == 1) {
            this.$message.warning('工艺版本号不能为空')
            return
          }
          if (this.formData.model == '1' && this.formData.unmergeData.filter(item => !item.engineeringBomId).length > 0 && e == 1) {
            this.$message.warning('BOM版本号不能为空')
            return
          }
          if (this.formData.model == '1' && this.formData.unmergeData.filter(item => !item.engineeringPathId).length > 0 && e == 1) {
            this.$message.warning('工艺路线不能为空')
            return
          }
          if (this.formData.unmergeData.filter(item => !this.SETTINGS.reg_no_zero.test(item.planNumber)).length > 0 && e == 1) {
            this.$message.warning('计划数量未正确填写')
            return
          }
          //  else if (this.formData.data.filter(item => item.willDeliverNumber && !this.SETTINGS.reg_no_zero.test(item.willDeliverNumber)).length > 0) {
          //   this.$message.warning('计划数量未正确填写')
          //   return
          // }
          if (this.formData.unmergeData.length == 0 && e == 1) {
            this.$message.warning('请添加物料明细')
            return
          } else {
            this.formData.planTime = this.formData.planTime ? moment(this.formData.planTime).format('YYYY-MM-DD') : ''
            const json = this.$deepClone(this.formData.unmergeData)
            if (this.formData.model == '0') {
              json.forEach(item => {
                item.engineeringBomId = ''
                item.engineeringBomCode = ''
                item.engineeringBomVersion = ''
                item.engineeringPathId = ''
                item.engineeringPathCode = ''
                item.engineeringPathName = ''
                item.engineeringPathVersion = ''
              })
            }
            if (this.formData.model == '1') {
              json.forEach(item => {
                item.engineeringRequirementId = ''
                item.engineeringRequirementCode = ''
                item.engineeringRequirementVersionCode = ''
              })
            }

            console.log('json', json)
            addOrUpdate({ ...this.formData, status: e, unmergeData: json }).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.refresh() // 调用父组件的刷新方法
            })
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
      //
    },
    importSpareParts() { // 导入备件物料
      this.$layer.iframe({// 弹框
        content: {
          content: ImportData, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['440px', '250px'],
        title: '导入数据', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    setRowBom() { // 设置每一行的BOM下拉框
      const cacheTableData = this.$deepClone(this.tableData)
      this.tableData = []
      const promises = []
      cacheTableData.forEach((item, index) => {
        if (!item.BOMList) {
          promises.push(BOMList({
            pageSize: 0,
            status: 1,
            materialId: item.materialId,
            orderByColumn: 'id',
            isAsc: 'desc'
          }))
        }
      })
      Promise.all(promises).then(res => {
        res.forEach((item, index) => {
          if (item.data && item.data.length > 0) {
            cacheTableData.forEach((item2, index2) => {
              if (item2.materialId == item.data[0].materialId) {
                item2.BOMList = item.data
                if (!item2.engineeringBomId) {
                  item2.engineeringBomId = item.data[item.data.length - 1].id
                  item2.engineeringBomCode = item.data[item.data.length - 1].code
                  item2.engineeringBomVersion = item.data[item.data.length - 1].versionCode
                  this.changeBOM(item2)
                }
                if (!item2.engineeringPathId) {
                  // 通过物料编码，查询工艺路线名称
                  choosePath_API(
                    {
                      name: item2.materialCode,
                      orderByColumn: 'id',
                      isAsc: 'desc',
                      status: 1
                    }).then(res2 => {
                    if (res2.data && res2.data.length > 0) {
                      this.chooseProcessFlowCallBack(res2.data[0], index2)
                    }
                  })
                }
              }
            })
          }
        })
        this.tableData = cacheTableData
        this.getWaringList_BOM()
      })
    },
    setRowRequirement() { // 设置每一行的工艺要求下拉框
      const cacheTableData = this.$deepClone(this.tableData)
      this.tableData = []
      const promises = []
      cacheTableData.forEach((item, index) => {
        promises.push(requirement(item.materialId))
      })
      Promise.all(promises).then(res => {
        res.forEach((item, index) => {
          if (item.data && item.data.length > 0) {
            console.log(item.data)
            console.log(cacheTableData)
            cacheTableData.forEach((item2, index2) => {
              if (item2.materialId == item.data[0].materialId) {
                item.data.forEach(item3 => {
                  item3.engineeringRequirementId = item3.id
                  item3.engineeringRequirementCode = item3.code
                  item3.engineeringRequirementVersionCode = item3.versionCode
                })
                item2.technologyVersionList = item.data
                if (!item2.engineeringRequirementId && item.data && item.data.length > 0) {
                  item2.engineeringRequirementId = item.data[0].id
                  item2.engineeringRequirementCode = item.data[0].code
                  item2.engineeringRequirementVersionCode = item.data[0].versionCode
                }
              }
            })
          }
        })
        this.tableData = cacheTableData
        this.getWaringList(cacheTableData)
      })
    },
    chooseProcessFlow(row, index) {
      this.$layer.iframe({
        // 弹框
        content: {
          content: ChooseProcessFlow, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: row.engineeringPathId,
            currentIndex: index
          }
        },
        area: ['880px', '700px'],
        title: '选择工艺路线', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseProcessFlowCallBack(row, index) {
      const cacheTableData = this.$deepClone(this.tableData)
      cacheTableData[index].engineeringPathId = row.id
      cacheTableData[index].engineeringPathCode = row.code
      cacheTableData[index].engineeringPathName = row.name
      cacheTableData[index].engineeringPathVersion = row.versionCode
      this.tableData = cacheTableData

      if (this.formData.saleOrderId) {
        this.unMergeList.forEach((item) => {
          if (item.saleOrderDetailId == cacheTableData[index].saleOrderDetailId) {
            item.engineeringPathId = row.id
            item.engineeringPathCode = row.code
            item.engineeringPathName = row.name
            item.engineeringPathVersion = row.versionCode
          }
        })
      } else {
        this.unMergeList.forEach((item) => {
          if (item.materialId == cacheTableData[index].materialId) {
            item.engineeringPathId = row.id
            item.engineeringPathCode = row.code
            item.engineeringPathName = row.name
            item.engineeringPathVersion = row.versionCode
          }
        })
      }
    },
    inputRadio(val) {
      const cacheTableData = this.$deepClone(this.tableData)
      this.tableData = []
      setTimeout(() => {
        this.tableData = cacheTableData
        if (val == 0) {
          this.setRowRequirement()
        }
        if (val == 1) {
          this.setRowBom()
        }
      }, 10)
    }
  }
}
</script>

<style lang="less" scoped>
// .main_enterWarehouseInvoices {
//   margin-left: 50px;
// }
.MaterialName {
  display: flex;
  padding: 15px;
  flex: 1;
  color:rgb(244,156,31);
  text-align: center;
  font-size: 16px;
  align-items: center;
  margin-bottom: 3px;
.MaterialNameName{
  //max-width: 150px;
  //  overflow: hidden;
  //white-space: nowrap;
  //text-overflow: ellipsis;
}
  .MaterialNameIcon {
    padding: 2px 5px 0 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

</style>
